package com.ruoyi.record.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.api.system.domain.SysDept;
import com.ruoyi.api.system.mapper.SysDeptMapper;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.basic.service.IBasicUserService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.record.domain.RecordDept;
import com.ruoyi.record.mapper.RecordDeptMapper;
import com.ruoyi.record.service.IRecordDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.text.Convert;

/**
 * 科室调整记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-05-26
 */
@Service
public class RecordDeptServiceImpl extends ServiceImpl<RecordDeptMapper, RecordDept> implements IRecordDeptService
{
    @Autowired
    private IBasicUserService basicUserService;

    @Autowired
    private BasicUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询科室调整记录
     * 
     * @param id 科室调整记录主键
     * @return 科室调整记录
     */
    @Override
    public RecordDept selectRecordDeptById(Long id)
    {
        return baseMapper.selectRecordDeptById(id);
    }

    /**
     * 查询科室调整记录列表
     * 
     * @param recordDept 科室调整记录
     * @return 科室调整记录
     */
    @Override
    public List<RecordDept> selectRecordDeptList(RecordDept recordDept)
    {
        return baseMapper.selectRecordDeptList(recordDept);
    }

    /**
     * 新增科室调整记录
     * 
     * @param recordDept 科室调整记录
     * @return 结果
     */
    @Override
    public int insertRecordDept(RecordDept recordDept)
    {
        if (recordDept.getIsDefault().equals("Y")){
            baseMapper.update(null, new LambdaUpdateWrapper<RecordDept>().set(RecordDept::getIsDefault, "N")
                    .eq(RecordDept::getUserId, recordDept.getUserId()).eq(RecordDept::getIsDefault, "Y"));

            BasicUser basicUser = basicUserService.selectBasicUserById(recordDept.getUserId());
            basicUser.setDeptId(recordDept.getDeptId());
            basicUserService.updateBasicUser(basicUser);
        }
        recordDept.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(recordDept);
    }

    /**
     * 修改科室调整记录
     *
     * @param recordDept 科室调整记录
     * @return 结果
     */
    @Override
    public int updateRecordDept(RecordDept recordDept)
    {
        if (recordDept.getIsDefault().equals("Y")){
            baseMapper.update(null, new LambdaUpdateWrapper<RecordDept>().set(RecordDept::getIsDefault, "N")
                    .eq(RecordDept::getUserId, recordDept.getUserId()).eq(RecordDept::getIsDefault, "Y")
                    .ne(RecordDept::getId, recordDept.getId()));

            BasicUser basicUser = basicUserService.selectBasicUserById(recordDept.getUserId());
            basicUser.setDeptId(recordDept.getDeptId());
            basicUserService.updateBasicUser(basicUser);
        }
        recordDept.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(recordDept);
    }

    /**
     * 批量删除科室调整记录
     * 
     * @param ids 需要删除的科室调整记录主键
     * @return 结果
     */
    @Override
    public int deleteRecordDeptByIds(String ids)
    {
        RecordDept recordDept = baseMapper.selectRecordDeptById(Long.parseLong(ids));
        if (recordDept.getIsDefault().equals("Y")){
            BasicUser basicUser = basicUserService.selectBasicUserById(recordDept.getUserId());
            basicUser.setDeptId(recordDept.getOldId());
            basicUserService.updateBasicUser(basicUser);
        }
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(ids)));
    }

    /**
     * 删除科室调整记录信息
     * 
     * @param id 科室调整记录主键
     * @return 结果
     */
    @Override
    public int deleteRecordDeptById(Long id)
    {
        return baseMapper.deleteById(id);
    }

    /**
     * 导入科室调整记录
     *
     * @param deptList 科室调整记录
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importRecordDept(List<RecordDept> deptList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(deptList) || deptList.size() == 0)
        {
            throw new ServiceException("导入科室调整记录不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecordDept recordDept : deptList)
        {
            try
            {
                //获取用户信息
                BasicUser user = userMapper.selectOne(new LambdaQueryWrapper<BasicUser>()
                        .eq(BasicUser::getIdCard, recordDept.getIdCard()).last("limit 1"));
                if(StringUtils.isNotNull(user)) {
                    recordDept.setUserId(user.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工" + recordDept.getUserName() + " 不存在");
                    continue;
                }

                SysDept oldDept = deptMapper.selectOne(new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getDeptName, recordDept.getOldName()).last("limit 1"));
                if(StringUtils.isNotNull(oldDept)) {
                    recordDept.setOldId(oldDept.getDeptId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，原科室" + recordDept.getOldName() + " 不存在");
                    continue;
                }

                SysDept newDept = deptMapper.selectOne(new LambdaQueryWrapper<SysDept>()
                        .eq(SysDept::getDeptName, recordDept.getDeptName()).last("limit 1"));
                if(StringUtils.isNotNull(newDept)) {
                    recordDept.setDeptId(newDept.getDeptId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，调整科室" + recordDept.getDeptName() + " 不存在");
                    continue;
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(recordDept.getChangeTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date changeTime = dateFormat.parse(recordDept.getChangeTime());
                    recordDept.setChangeTime(DateUtils.parseDateToStr("yyyy-MM-dd", changeTime));
                }

                RecordDept info = baseMapper.selectOne(new LambdaQueryWrapper<RecordDept>()
                        .eq(RecordDept::getOldName, recordDept.getOldName())
                        .eq(RecordDept::getDeptName, recordDept.getDeptName())
                        .eq(RecordDept::getChangeTime, recordDept.getChangeTime())
                        .eq(RecordDept::getUserId, recordDept.getUserId()).last("limit 1"));
                if (StringUtils.isNull(info))
                {
                    recordDept.setCreateBy(operName);
                    this.insertRecordDept(recordDept);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + recordDept.getUserName() + "科室调整记录 " + recordDept.getOldName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    recordDept.setId(info.getId());
                    recordDept.setUpdateBy(operName);
                    this.updateRecordDept(recordDept);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + recordDept.getUserName() + "科室调整记录 " + recordDept.getOldName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工 " + recordDept.getUserName() + "科室调整记录 " + recordDept.getOldName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + recordDept.getUserName() + " 科室调整记录导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询科室调整记录
     *
     * @param loginName 科室调整记录主键
     * @return 科室调整记录
     */
    @Override
    public List<RecordDept> selectRecordDeptByLoginName(String loginName)
    {
        return baseMapper.selectRecordDeptByLoginName(loginName);
    }
}
